#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <set>
#include "tree.h"

using namespace std;

Tree *findNode(Tree *root, int data)
{
   if (root->data == data) {
       return root;    
   }
   if (root->data > data) 
       return findNode(root->left, data);
   else 
       return findNode(root->right, data);
}

Tree *findMin(Tree *node)
{
    while (node->left)
        node = node->left;
    return node;
}

Tree *successor(Tree *node)
{
    if (!node) return NULL;
    if (node->right) return findMin(node->right);
    Tree *parent = node->parent;
    while(parent && node== parent->right) {
        node = parent;
        parent = node->parent;
    }
    return parent;
}

int main(int argc, char **argv)
{
    int input[] = {21,7,5,6,3,2,1,4,6,23,43,54,12,54,8,10,11,35,56};
    //int input[] = {7};
    Tree *root = NULL, *root2 = NULL;
    int result;

    for (int i = 0; i < sizeof(input)/sizeof(int); i++) {
        TreeInsert(root, input[i], NULL);
    }
    print_ascii_tree(root);
    int ch;
    while(1) {
        cout << "Input your choice: " << endl;
        cin >> ch;
        cout << "Find " << ch << endl;
        Tree *target = findNode(root, ch);
        Tree *node = successor(target);
        if (node) cout << "sucessor is " << node->data << endl;
        else cout << "Does not exist " << endl;
    }
}
